package ro.upt.dcda.web.admin;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.jms.StreamMessage;

import ro.upt.dcda.pricezone.common.Config;
import ro.upt.dcda.pricezone.common.Config.ServerInfo;
import ro.upt.dcda.pricezone.common.JMSMediator;
import ro.upt.dcda.pricezone.common.Server;
import ro.upt.dcda.pricezone.common.StoreData;
import ro.upt.dcda.pricezone.s1.pojo.Admin;

import com.opensymphony.xwork2.ActionContext;

public class AdminViewStoresServlet {

	private List<StoreData> stores = new ArrayList<StoreData>();
	private List<String> servers;
	private String serverName;

	public String getServerName() {
		return serverName;
	}

	public void setServerName(String serverName) {
		this.serverName = serverName;
	}

	public String execute() throws Exception {
		System.out.println("Viewing stores");
		Map<String, Object> session = ActionContext.getContext().getSession();
		Admin admin = (Admin) session.get("admin");
		String adminSid = (String) session.get("adminSid");
		if (admin == null || adminSid == null) {
			return "noAuth";
		}
		servers = new ArrayList<String>();
		for (ServerInfo serverInfo : Config.getServerList()) {
			servers.add(serverInfo.getName());
		}
		if (serverName == null) {
			return "def";
		}
		Server server = JMSMediator.getMediator().getServerByName(serverName);
		if (server == null) {
			System.out.println("Server " + serverName + " not found");
			return "def";
		}
		StreamMessage msg = server.createStreamMessage();
		msg.writeString("allStores");
		StreamMessage response = (StreamMessage) server.getResponseFor(msg,
				20000);
		if (response == null) {
			return "def";
		}
		int nr = response.readInt();
		for (int i = 0; i < nr; i++) {
			StoreData store = new StoreData();
			store.id = response.readInt();
			store.name = response.readString();
			store.description = response.readString();
			store.location = response.readString();
			store.server = response.readString();
			stores.add(store);
		}
		return "def";
	}

	public String getDefaultServers() {
		return servers.size() > 0 ? servers.get(0) : "";
	}

	public List<String> getServers() {
		return servers;
	}

	public void setServers(List<String> servers) {
		this.servers = servers;
	}

	public List<StoreData> getStores() {
		return stores;
	}

	public void setStores(List<StoreData> stores) {
		this.stores = stores;
	}
}
